import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from '@/router/routes'
import store from '@/store'
//重写vueRouter实例的push方法
Vue.use(VueRouter)
    //先保存一份
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

//重写push
VueRouter.prototype.push = function(location, resolve, reject) {
        if (reject && resolve) {
            //使用call篡改上下文
            originPush.call(this, location, reject, resolve)
        } else {
            originPush.call(this, location, () => {}, () => {})
        }
    }
    //重写replace
VueRouter.prototype.replace = function(location, resolve, reject) {
    if (reject && resolve) {
        //使用call篡改上下文
        originReplace.call(this, location, reject, resolve)
    } else {
        originReplace.call(this, location, () => {}, () => {})
    }
}

// 配置路由
let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        // `to` 和 `from` 都是路由地址
        // `savedPosition` 可以为空，如果没有的话。
        return { y: 0 }
    }

})

// 设置路由守卫
router.beforeEach(async(to, from, next) => {

    let token = store.state.login.token
    let userInfo = store.state.login.userInfo
    if (token) {
        if (to.path == '/login') {
            next('/home')
        } else {
            if (userInfo.name) {
                next()
            } else {
                // 获取用户信息
                try {
                    await store.dispatch('loginSucc')
                    next()
                } catch (error) {
                    await store.dispatch('layout')
                    next('/login')
                }
            }

        }
    } else {
        let toPath = to.path
        console.log(toPath);
        if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/center') != -1 || toPath.indexOf('/paySuccess') != -1 || toPath.indexOf('/pay') != -1) {
            next('/login?redirect=' + toPath)
        } else {
            next()
        }
    }
});
export default router